package com.huaxin.hxcloud.frendcircles;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.FindInfo;
import com.huaxin.common.Global;
import com.huaxin.common.frendcircle.bean.CommentItem;
import com.huaxin.common.frendcircle.utils.CommonUtils;
import com.huaxin.common.frendcircle.widgets.CommentListView;
import com.huaxin.common.frendcircle.widgets.DivItemDecoration;
import com.huaxin.common.frendcircle.widgets.TitleBar;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.find.HttpCommit;
import com.huaxin.hxcloud.find.SendCommentActivity;
import com.huaxin.hxcloud.find.view.CommentEventBus;
import com.huaxin.hxcloud.find.view.HxCommentContentEventBus;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static java.lang.Integer.parseInt;

/**
 * 评论界面
 */
public class FrendCircleActivity extends AppCompatActivity implements CircleContract.View, View.OnClickListener {
    //
    private CircleAdapter circleAdapter;
    private LinearLayout  edittextbody;
    private EditText      editText;
    private TextView      sendIv;

    private int screenHeight;
    private int editTextBodyHeight;
    private int currentKeyboardH;
    private int selectCircleItemH;
    private int selectCommentItemOffset;

    private CirclePresenter     presenter;
    private CommentConfig       commentConfig;
    private RelativeLayout      bodyLayout;
    private RecyclerView        recyclerView;
    private XRefreshView        xRefreshView;
    private LinearLayoutManager layoutManager;
    private TitleBar            titleBar;

    private final static int TYPE_PULLREFRESH   = 1;
    private final static int TYPE_UPLOADREFRESH = 2;
    //
    private FindInfo.QuestionListBean questionListBean;
    private int                       position;
    private int                       type;
    private LinearLayout              buttomNav;
    private int                       questionId;

    private RelativeLayout collectionRv;
    private TextView       collectTv;
    private RelativeLayout commentRv;

    private RelativeLayout zanRv;
    private TextView       zanTv;

    private              boolean isLikeer      = false;//当前用户是否点赞
    private              boolean isCollect     = false;//当前用户是否收藏，默认false
    private              int     mCommentCount = 0; //评论次数
    private static final String  TAG           = "FrendCircleActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_frend_circle);
        //朋友圈的处理类
        presenter = new CirclePresenter(this, this);
        //拿到评论
        questionListBean = (FindInfo.QuestionListBean) getIntent().getSerializableExtra("user");
        //拿到说说的位置
        // position = getIntent().getIntExtra("position", 0);
        //拿到类型（全部，企业，好友...）
        // type = getIntent().getIntExtra("type", 0);
        if (questionListBean != null) {
            questionId = questionListBean.getQuestionId();
            isLikeer = questionListBean.isIsLike();
            isCollect = questionListBean.isIsCollection();
        }
        initView();
    }

    @Override
    protected void onDestroy() {
        if (presenter != null) {
            presenter.recycle();
        }
        super.onDestroy();
    }

    @SuppressLint({"ClickableViewAccessibility", "InlinedApi"})
    public void initView() {
        //收藏
        collectionRv = (RelativeLayout) findViewById(R.id.frend_circle_collection);
        collectTv = (TextView) findViewById(R.id.find_collect);
        if (isCollect) {
            Drawable drawable = getResources().getDrawable(R.drawable.star_selected);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            collectTv.setCompoundDrawables(drawable, null, null, null);
        }
        collectionRv.setOnClickListener(this);
        //评论
        commentRv = (RelativeLayout) findViewById(R.id.frend_circle_comment);
        commentRv.setOnClickListener(this);
        //点赞
        zanRv = (RelativeLayout) findViewById(R.id.frend_circle_zan);
        zanRv.setOnClickListener(this);
        zanTv = (TextView) findViewById(R.id.find_zan1);
        if (isLikeer) {
            Drawable drawable = getResources().getDrawable(R.drawable.love_selected);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            zanTv.setCompoundDrawables(drawable, null, null, null);
        }
        //toorbar
        titleBar = (TitleBar) findViewById(R.id.main_title_bar);
        titleBar.setTitle("评论");
        titleBar.setTitleColor(getResources().getColor(R.color.gray));
        titleBar.setBackgroundColor(getResources().getColor(R.color.white));
        titleBar.setLeftImageResource(R.drawable.icon_back_f);
        titleBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshBackData();
            }
        });

        xRefreshView = (XRefreshView) findViewById(R.id.find_activity_xrefresh);
        xRefreshView.setPullRefreshEnable(true);
        xRefreshView.setPullLoadEnable(false);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DivItemDecoration(2, true));
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (edittextbody.getVisibility() == View.VISIBLE) {
                    updateEditTextBodyVisible(View.GONE, null);
                    return true;
                }
                return false;
            }
        });
        //刷新
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh(boolean isPullDown) {
                super.onRefresh(isPullDown);
                presenter.loadData(TYPE_PULLREFRESH, questionId);//加载数据
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        xRefreshView.stopRefresh();
                    }
                }, 500);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
            }
        });
        //评论的适配器
        circleAdapter = new CircleAdapter(this);
        circleAdapter.setActivity(this);
        circleAdapter.setCirclePresenter(presenter);
        circleAdapter.setquestionListBean(questionListBean);
        recyclerView.setAdapter(circleAdapter);
        presenter.loadData(TYPE_PULLREFRESH, questionId);//加载数据

        edittextbody = (LinearLayout) findViewById(R.id.editTextBodyLl);
        editText = (EditText) findViewById(R.id.circleEt);
        sendIv = (TextView) findViewById(R.id.sendIv);
        buttomNav = (LinearLayout) findViewById(R.id.friend_buttom_ll);
        //
        sendIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (presenter != null) {
                    //发布评论
                    String content = editText.getText().toString().trim();
                    if (TextUtils.isEmpty(content)) {
                        Toast.makeText(FrendCircleActivity.this, "评论内容不能为空...", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    presenter.addComment(content, commentConfig);
                }
                updateEditTextBodyVisible(View.GONE, null);
            }
        });
        //计算高度，保证键盘不遮挡评论
        setViewTreeObserver();
    }

    private void setViewTreeObserver() {
        bodyLayout = (RelativeLayout) findViewById(R.id.bodyLayout);
        final ViewTreeObserver swipeRefreshLayoutVTO = bodyLayout.getViewTreeObserver();
        swipeRefreshLayoutVTO.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                bodyLayout.getWindowVisibleDisplayFrame(r);
                int statusBarH = getStatusBarHeight();//状态栏高度
                int screenH = bodyLayout.getRootView().getHeight();
                if (r.top != statusBarH) {
                    r.top = statusBarH;
                }
                int keyboardH = screenH - (r.bottom - r.top);
                if (keyboardH == currentKeyboardH) {//有变化时才处理，否则会陷入死循环
                    return;
                }
                currentKeyboardH = keyboardH;
                screenHeight = screenH;//应用屏幕的高度
                editTextBodyHeight = edittextbody.getHeight();
                if (keyboardH < 150) {//说明是隐藏键盘的情况
                    updateEditTextBodyVisible(View.GONE, null);
                    return;
                }
                if (layoutManager != null && commentConfig != null) {
                    layoutManager.scrollToPositionWithOffset(commentConfig.circlePosition + CircleAdapter.HEADVIEW_SIZE, getListviewOffset(commentConfig));
                }
            }
        });
    }

    //计算toorBar 的 高度
    private int getStatusBarHeight() {
        int result = 0;
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    //监听返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (edittextbody != null && edittextbody.getVisibility() == View.VISIBLE) {
                updateEditTextBodyVisible(View.GONE, null);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /*
    * 删除问题
    * */
    @Override
    public void update2DeleteCircle(String circleId) {
        List<CircleItem> circleItems = circleAdapter.getDatas();
        for (int i = 0; i < circleItems.size(); i++) {
            if (circleId.equals(circleItems.get(i).getId())) {
                //
                CircleItem circleItem = circleItems.get(i);


                int commentNum = circleAdapter.getQuestionListBean().getCommentNum();
                if (commentNum > 0) {
                    circleAdapter.getQuestionListBean().setCommentNum(commentNum - 1);
                } else {
                    circleAdapter.getQuestionListBean().setCommentNum(0);
                }
                int parentId = circleItem.getParentId();
                HttpCommit.comitDelete(parentId);

                //删除评论Event
                FindInfo.QuestionListBean.PartialTopCommentArrBean commentArrBean = new FindInfo.QuestionListBean.PartialTopCommentArrBean();
                commentArrBean.setContent(circleItem.getContent());
                FindInfo.QuestionListBean.PartialTopCommentArrBean.PublisherBeanX publisherBeanX = new FindInfo.QuestionListBean.PartialTopCommentArrBean.PublisherBeanX();
                publisherBeanX.setId(Integer.parseInt(circleItem.getUser().getId()));
                publisherBeanX.setImg(circleItem.getUser().getHeadUrl());
                publisherBeanX.setNickName(circleItem.getUser().getName());
                commentArrBean.setPublisher(publisherBeanX);
                EventBus.getDefault().post(new HxCommentContentEventBus(commentArrBean, questionId, HxCommentContentEventBus.DELECT_COMMENT));

                circleItems.remove(i);
                circleAdapter.notifyDataSetChanged();
                return;
            }
        }
    }

    /*
    * 发表评论
    * */
    @Override
    public void update2AddComment(int circlePosition, CommentItem addItem) {
        if (addItem != null) {
            CircleItem itemx = (CircleItem) circleAdapter.getDatas().get(circlePosition);
            int parentId = itemx.getParentId();
            if (addItem.getToReplyUser() != null) {
                int toUserId = parseInt(addItem.getToReplyUser().getId());
                sendComment(addItem.getContent(), parentId, toUserId, 1);
            } else {
                int toUserId = Integer.parseInt(itemx.getUser().getId());
                sendComment(addItem.getContent(), parentId, toUserId, 0);
            }
            CircleItem item = (CircleItem) circleAdapter.getDatas().get(circlePosition);
            item.getComments().add(addItem);
            circleAdapter.notifyDataSetChanged();
        }
        mCommentCount++;//评论数
        //清空评论文本
        editText.setText("");
    }

    //上传评论的方法
    private void sendComment(String content, int parentId, int toUserId, int response) {
        if (null != content) {
            Call<BaseDTO> call = RequestHelper.getRequestApi().commitComment2(questionId, parentId, content, toUserId, response, null);
            call.enqueue(new Callback<BaseDTO>() {
                @Override
                public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                    if (response.isSuccessful()) {
                    } else {
                        ToastUtil.showToastShort("提交失败");
                    }
                }

                @Override
                public void onFailure(Call<BaseDTO> call, Throwable t) {
                    ToastUtil.showToastShort("网络故障");
                }
            });
        }
    }

    /*
    * 删除评论
    * */
    @Override
    public void update2DeleteComment(int circlePosition, String commentId) {
        CircleItem item = (CircleItem) circleAdapter.getDatas().get(circlePosition);
        List<CommentItem> items = item.getComments();
        for (int i = 0; i < items.size(); i++) {
            if (commentId.equals(items.get(i).getId())) {
                items.remove(i);
                circleAdapter.notifyDataSetChanged();
                return;
            }
        }
    }

    /*
    * 显示隐藏键盘的方法
    * */
    @Override
    public void updateEditTextBodyVisible(int visibility, CommentConfig commentConfig) {
        this.commentConfig = commentConfig;
        edittextbody.setVisibility(visibility);
        if (View.VISIBLE == visibility) {
            if (softState != null) {
                softState.onState(true);
            }
        } else if (View.GONE == visibility) {
            if (softState != null) {
                softState.onState(false);
            }
        }
        measureCircleItemHighAndCommentItemOffset(commentConfig);
        if (View.VISIBLE == visibility) {
            editText.requestFocus();
            CommonUtils.showSoftInput(editText.getContext(), editText);
            buttomNav.setVisibility(View.GONE);
        } else if (View.GONE == visibility) {
            CommonUtils.hideSoftInput(editText.getContext(), editText);
            buttomNav.setVisibility(View.VISIBLE);
        }
    }

    //
    public interface OnSoftState {
        void onState(boolean flags);
    }

    public OnSoftState softState;

    public void setSoftState(OnSoftState softState) {
        this.softState = softState;
    }

    /**
     * 数据回调的接口
     */
    @Override
    public void update2loadData(int loadType, List<CircleItem> datas) {
        if (loadType == TYPE_PULLREFRESH) {
            circleAdapter.setDatas(datas);
        } else if (loadType == TYPE_UPLOADREFRESH) {
            circleAdapter.getDatas().addAll(datas);
        }
        circleAdapter.notifyDataSetChanged();
    }

    /**
     * 测量偏移量
     */
    private int getListviewOffset(CommentConfig commentConfig) {
        if (commentConfig == null)
            return 0;
        int listviewOffset = screenHeight - selectCircleItemH - currentKeyboardH - editTextBodyHeight - titleBar.getHeight();
        if (commentConfig.commentType == CommentConfig.Type.REPLY) {
            //回复评论的情况
            listviewOffset = listviewOffset + selectCommentItemOffset;
        }
        return listviewOffset;
    }

    //测量回复的高度
    private void measureCircleItemHighAndCommentItemOffset(CommentConfig commentConfig) {
        if (commentConfig == null)
            return;
        int firstPosition = layoutManager.findFirstVisibleItemPosition();
        View selectCircleItem = layoutManager.getChildAt(commentConfig.circlePosition + CircleAdapter.HEADVIEW_SIZE - firstPosition);
        if (selectCircleItem != null) {
            selectCircleItemH = selectCircleItem.getHeight();
        }
        if (commentConfig.commentType == CommentConfig.Type.REPLY) {
            CommentListView commentLv = (CommentListView) selectCircleItem.findViewById(R.id.commentList);
            if (commentLv != null) {
                View selectCommentItem = commentLv.getChildAt(commentConfig.commentPosition);
                if (selectCommentItem != null) {
                    selectCommentItemOffset = 0;
                    View parentView = selectCommentItem;
                    do {
                        int subItemBottom = parentView.getBottom();
                        parentView = (View) parentView.getParent();
                        if (parentView != null) {
                            selectCommentItemOffset += (parentView.getHeight() - subItemBottom);
                        }
                    } while (parentView != null && parentView != selectCircleItem);
                }
            }
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.frend_circle_comment://发送评论
                Intent intent = new Intent(this, SendCommentActivity.class);
                intent.putExtra("questionId", questionListBean.getQuestionId());
                intent.putExtra("toUserId", questionListBean.getPublisher().getId());
                startActivityForResult(intent, 0);
                break;
            case R.id.frend_circle_collection:
                final int collectionNum = questionListBean.getCollectionNum();
                Log.d(TAG, "onClick: --collectionsize11--->" + questionListBean.getCollectionNum());
                HttpCommit httpCommit = new HttpCommit();
                httpCommit.commitCollection(questionId);
                httpCommit.setIsResponse(new HttpCommit.IsResponse() {
                    @Override
                    public void OnClock(boolean flag) {
                        if (flag) {
                            //收藏
                            if (isCollect) {
                                Drawable drawable = getResources().getDrawable(R.drawable.star_normal);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                collectTv.setCompoundDrawables(drawable, null, null, null);
                                isCollect = false;
                                questionListBean.setIsCollection(false);
                                if (collectionNum == 0) {
                                    questionListBean.setCollectionNum(0);
                                } else {
                                    questionListBean.setCollectionNum(collectionNum - 1);
                                }
                            } else {
                                questionListBean.setCollectionNum(collectionNum + 1);
                                Drawable drawable = getResources().getDrawable(R.drawable.star_selected);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                collectTv.setCompoundDrawables(drawable, null, null, null);
                                AnimationTools.scale(collectTv);
                                isCollect = true;
                                questionListBean.setIsCollection(true);
                            }
                        }
                        circleAdapter.notifyDataSetChanged();
                    }
                });
                Log.d(TAG, "onClick: --collectionsize22--->" + questionListBean.getCollectionNum());
                break;
            case R.id.frend_circle_zan:
                final int likeerNum = questionListBean.getLikeerNum();
                //赞
                String imgUrl = Global.user.getImgUrl();
                String nickName = Global.user.getNickName();
                Integer userId = Global.user.getUserId();
                final FindInfo.LikeerArrayBean likeerArrayBean = new FindInfo.LikeerArrayBean();
                likeerArrayBean.setId(userId);
                likeerArrayBean.setImg(imgUrl);
                likeerArrayBean.setNickName(nickName);
                final List<FindInfo.LikeerArrayBean> likeerArrayBeanList = questionListBean.getLikeerArray();

                HttpCommit httpCommit1 = new HttpCommit();
                httpCommit1.commitLike(questionId);
                httpCommit1.setIsResponse(new HttpCommit.IsResponse() {
                    @Override
                    public void OnClock(boolean flag) {
                        if (flag) {
                            if (!isLikeer) {
                                Drawable drawable = getResources().getDrawable(R.drawable.love_selected);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                zanTv.setCompoundDrawables(drawable, null, null, null);
                                AnimationTools.scale(zanTv);
                                isLikeer = true;
                                questionListBean.setIsLike(true);
                                likeerArrayBeanList.add(likeerArrayBean);
                                questionListBean.setLikeerNum(likeerNum + 1);
                                Log.d(TAG, "OnClock: ---11-->" + likeerArrayBeanList.toString());
                            } else {
                                Drawable drawable = getResources().getDrawable(R.drawable.love_normal);
                                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                                zanTv.setCompoundDrawables(drawable, null, null, null);
                                isLikeer = false;
                                questionListBean.setIsLike(false);
                                for (int i = 0; i < likeerArrayBeanList.size(); i++) {
                                    if (likeerArrayBeanList.get(i).getId() == Global.user.getUserId()) {
                                        likeerArrayBeanList.remove(i);
                                    }
                                }
                                if (likeerNum == 0) {
                                    questionListBean.setLikeerNum(0);
                                } else {
                                    questionListBean.setLikeerNum(likeerNum - 1);
                                }
                                Log.d(TAG, "OnClock: ---22-->" + likeerArrayBeanList.toString());
                                Log.d(TAG, "OnClock: ----id--->" + Global.user.getUserId());
                            }
                        }
                        circleAdapter.notifyDataSetChanged();
                    }
                });
                Log.d(TAG, "OnClock: ---33-->" + likeerArrayBeanList.toString());


                break;
        }
    }

    /*
    * 发表评论后的更新数据
    * */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (data.getIntExtra("code", 0) == 1) {
                presenter.loadData(TYPE_PULLREFRESH, questionId);//加载数据
                int commentNum = circleAdapter.getQuestionListBean().getCommentNum();
                circleAdapter.getQuestionListBean().setCommentNum(commentNum + 1);
                circleAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        refreshBackData();
    }

    /**
     * 返回时刷新适配器
     */
    private void refreshBackData() {
        FindInfo.QuestionListBean listBean = circleAdapter.getQuestionListBean();
        int questionId = questionListBean.getQuestionId();
        boolean isLike = listBean.isIsLike();
        int likeerNum = listBean.getLikeerNum();

        boolean isCollection = listBean.isIsCollection();
        int collectionNum = listBean.getCollectionNum();

        int commentNum = listBean.getCommentNum();

        //点赞头像集合
        List<FindInfo.LikeerArrayBean> likeerArray = questionListBean.getLikeerArray();

        EventBus.getDefault().post(new CommentEventBus(questionId, isLike, likeerNum, isCollection, collectionNum, commentNum, likeerArray));
        finish();
    }
}
